package com.ryan.ohos.extension.widget.expandablelist;


import java.util.ArrayList;


public abstract class Observable<T> {

    protected final ArrayList<T> mObservers = new ArrayList<T>();

    /**
     * addObserver
     *
     * @param observer observer
     * @throws IllegalArgumentException The observer is null.
     * @throws IllegalStateException    The observer is null.
     */
    public void addObserver(T observer) {
        if (observer == null) {
            throw new IllegalArgumentException("The observer is null.");
        }
        synchronized (mObservers) {
            if (mObservers.contains(observer)) {
                throw new IllegalStateException("Observer " + observer + " is already registered.");
            }
            mObservers.add(observer);
        }
    }

    /**
     * removeObserver
     *
     * @param observer observer
     * @throws IllegalArgumentException The observer is null.
     * @throws IllegalStateException    The observer is null.
     */
    public void removeObserver(T observer) {
        if (observer == null) {
            throw new IllegalArgumentException("The observer is null.");
        }
        synchronized (mObservers) {
            int index = mObservers.indexOf(observer);
            if (index == -1) {
                throw new IllegalStateException("Observer " + observer + " was not registered.");
            }
            mObservers.remove(index);
        }
    }

    /**
     * unregisterAll
     */
    public void unregisterAll() {
        synchronized (mObservers) {
            mObservers.clear();
        }
    }
}

